//const Store = require("electron-store");
/**
 * 连接参数
 */

import Store from "electron-store";
import { uuid } from "../utils/uuid";

const store = new Store();

var key = "linkinfo";

var defaultLinkInfo = {
  id: "uuid",
  name: "本地连接",
  host: "localhost",
  port: "3306",
  user: "root",
  password: "bridge2018",
  database: "demo",
};

function obtain() {
  var list = store.get(key);
  if (list == null || list == undefined || list.length <= 0) {
    list = reset();
  }
  return list;
}

function add(linkInfo) {
  var list = obtain();
  let lll = {};
  Object.keys(defaultLinkInfo).forEach((key) => {
    lll[key] = linkInfo[key];
  });
  lll.id = uuid();
  list.push(lll);
  store.set(key, list);
}

function update(id, linkInfo) {
  var list = obtain();
  var index = list.findIndex((item) => item.id === id);
  if (index < 0) {
    return "not found";
  }
  let lll = {};
  Object.keys(defaultLinkInfo).forEach((key) => {
    lll[key] = linkInfo[key];
  });
  list.splice(index, 1, lll);
  store.set(key, list);
  return "success";
}

function remove(id) {
  var list = obtain();
  var index = list.findIndex((item) => item.id === id);
  if (index < 0) {
    return "not found";
  }
  list.splice(index, 1);
  store.set(key, list);
  return "success";
}

function list(like) {
  var list = obtain();
  //console.log(list);
  let filterList = list.filter((item) => {
    let n = item.name.includes(like);
    let h = item.host.includes(like);
    let u = item.user.includes(like);
    let result = n || h || u;
    return result;
  });
  return filterList;
}

function get(id) {
  var list = obtain();
  var index = list.findIndex((item) => item.id === id);
  if (index < 0) {
    return null;
  }
  return list[index];
}

function reset() {
  store.delete(key);
  defaultLinkInfo.id = uuid();
  store.set(key, [defaultLinkInfo]);
  return store.get(key);
}

let LinkStore = {
  add,
  update,
  remove,
  list,
  get,
  reset,
};

export default LinkStore;
